<?php namespace Admin\Model;

use Hdphp\Model\Model;

//后台用户表
class Admin extends Model{
	//定义模型
	protected $table = "Admin";

	//自动验证
	protected $validate = [
		['adminaccount','required','用户名不能为空',3,3],
		['adminpwd','required','密码不能为空',3,3],
		['adminname','required','昵称不能为空',3,3],
	];

	//自动完成
	protected $auto = [
		['registertime','time','function',3,1],
		['adminpwd','md5','function',3,3],
	];

	//验证验证码
	public function checkCode(){
		$code=Q('post.code','','strtoupper');//获取提交的验证码
		if ($code != strtoupper($_SESSION['code'])) return false;
		return true;
	}


	//添加管理员
	public function store(){
		$data=Q('post.');
		$adminroleModel=new AdminRole();
		//验证
		if(!$this->create()) return false;
		//合并重复的角色
		$data['group_id']=array_unique($data['group_id']);
		//添加管理员用户
		$aid=$this->add();
		foreach ($data['group_id'] as $v) {
			$adminroleModel->add(['user_id'=>$aid,'role_id'=>$v]);
		}
		return true;
	}

	//编辑管理员
	public function edit(){
		$data=Q('post.');
		$adminroleModel=new AdminRole();
		if(!$data['adminpwd']) $_POST['adminpwd']=$this->where("aid={$data['aid']}")->pluck('adminpwd');
		//验证
		if(!$this->create()) return false;
		//合并重复的角色
		$data['group_id']=array_unique($data['group_id']);
		//修改管理员信息
		$this->save();
		$adminroleModel->where("user_id={$data['aid']}")->delete();
		foreach ($data['group_id'] as $v) {
			$adminroleModel->add(['user_id'=>$data['aid'],'role_id'=>$v]);
		}
		return true;
	}

	//获得管理员数据
	public function getData(){
		$role_id=Q('get.role_id',0,'intval');
		if ($role_id) {
			$adminroleModel=new AdminRole();
			//获得拥有此角色id的用户id
			$aids=$adminroleModel->where("role_id={$role_id}")->lists('user_id');
			$aids=implode(',',$aids);
			//注册时间范围
			$begin_time=Q('get.st','')?strtotime(Q('get.st','')):0;
			$end_time=Q('get.et','')?strtotime(Q('get.et','')):time();
			//搜索的关键字
			$keyword=Q('get.keyword','_');
			//筛选条件
			$sqlwhere="registertime BETWEEN $begin_time AND $end_time AND aid IN ({$aids}) AND adminaccount like '%{$keyword}%' ";
			return $this->where($sqlwhere)->get();
		}else{
			return $this->get();
		}
	}

	//删除用户
	public function del($aid=0){
		$adminroleModel=new AdminRole();
		if ($num) {//删除单个用户
			$adminroleModel->where("user_id=$aid")->delete();
			$this->where("aid=$aid")->delete();
		}else{//删除选中用户
			foreach (Q('post.uid') as $v) {
				$adminroleModel->where("user_id=$v")->delete();
				$this->where("aid=$v")->delete();
			}
		}
	}

	//锁定用户
	public function lock(){
		foreach (Q('post.uid') as $v) {
			$this->where("aid=$v")->update(['islock'=>1]);
		}
	}

	//解锁用户
	public function unlock(){
		foreach (Q('post.uid') as $v) {
			$this->where("aid=$v")->update(['islock'=>0]);
		}
	}



}